using Admin2025.Application.common;
using Admin2025.Domain.Entities.App;
using Admin2025.Domain.Repository;

namespace Admin2025.Application.Services;

public class AuthService
{
    private readonly IRepository<AppUser> _userRepo;
    private readonly IRepository<AppRole> _roleRepo;
    public AuthService(IRepository<AppUser> userRepo, IRepository<AppRole> roleRepo)
    {
        _userRepo = userRepo;
        _roleRepo = roleRepo;
    }

    public async Task<ApiResult> RegisterAsync(string username, string password)
    {
        //1.检查用户名是否存在
        var exists = (await _userRepo.GetAllAsync()).Any(u => u.Username == username);
        if (exists)
        {
            Console.WriteLine("注册失败：用户名已存在");
            return ApiResult.Fail(3003, "用户名已存在");
        }
        // 2. 生成盐和加密密码
        var salt = Guid.NewGuid().ToString("N");
        var hashedPwd = HashPassword(password, salt);


        // 3. 分配默认角色
        var defaultRole = (await _roleRepo.GetAllAsync()).FirstOrDefault(r => r.RoleName == "User");
        if (defaultRole == null)
        {
            Console.WriteLine("注册失败：默认角色未找到");
            return ApiResult.Fail(3004, "默认角色未找到");
        }
        //创建用户
        var user = new AppUser
        {
            Username = username,
            Password = hashedPwd,
            Salt = salt
        };
        user.AssignRole(defaultRole);


        try
        {
            await _userRepo.CreateAsync(user);
            Console.WriteLine("注册成功");
            return ApiResult.Success("注册成功");
        }
        catch (Exception ex)
        {
             Console.WriteLine($"注册失败：{ex.Message}");
            return ApiResult.Fail(3005, $"注册失败：{ex.Message}");
        }
       
    }

    public async Task<ApiResult> LoginAsync(string username, string password)
    {
        var user = (await _userRepo.GetAllAsync()).FirstOrDefault(u => u.Username == username);
        if (user == null)
        {
            return ApiResult.Fail(3003, "账号不存在");
        }

        var hashedPwd = HashPassword(password, user.Salt);
        if (user.Password != hashedPwd)
        {
            return ApiResult.Fail(3003, "账号或者密码无效，请确认后重试");
        }

        return ApiResult.Success("登录成功");
    }

    //哈希算法
    private string HashPassword(string password, string salt)
    {
        using var sha256 = System.Security.Cryptography.SHA256.Create();
        var bytes = System.Text.Encoding.UTF8.GetBytes(password + salt);
        var hash = sha256.ComputeHash(bytes);
        return Convert.ToBase64String(hash);
    }
}